//
//  Utils.m
//  YHApp
//
//  Created by jqc on 16/6/13.
//  Copyright © 2016年 silysolong. All rights reserved.
//

#import "Utils.h"
#import <sys/utsname.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
//#import "TZImagePickerController.h"
//#import "RDBaseTabBarController.h"
//#import "RDBaseNavigationController.h"

@implementation Utils
+ (BOOL)checkPassword:(NSString *) password
{
    //    BOOL result=false;
    //    // 判断长度大于8位后再接着判断是否同时包含数字和字符
    //    NSString * regex = @"^(?![a-zA-Z0-9]+$)(?![^a-zA-Z/D]+$)(?![^0-9/D]+$).{6,12}$";
    //    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    //    result = [pred evaluateWithObject:password];
    //    return result;
    
    //    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}";
    //    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    //    BOOL isMatch = [pred evaluateWithObject:password];
    //    return isMatch;
    
    if (password.length >=6 && password.length <=20) {
        return YES;
    }else {
        return NO;
    }
}

+ (BOOL) isEmpty:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

+ (BOOL)isToday:(NSDate *)date
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    
    NSString *nowString = [fmt stringFromDate:[NSDate date]];
    NSString *selfString = [fmt stringFromDate:date];
    
    return [nowString isEqualToString:selfString];
}

+ (NSString *)compareTimeIsTodayWithDate:(NSDate *)date{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    
    NSString *nowString = [fmt stringFromDate:[NSDate date]];
    NSString *checkTimeStr = [fmt stringFromDate:date];
    
    if ([nowString isEqualToString:checkTimeStr]) {
        fmt.dateFormat = @"HH:mm";
        checkTimeStr = [fmt stringFromDate:date];
        return checkTimeStr;
    }else{
        return checkTimeStr;
    }
}

//验证手机号码
+ (BOOL)checkCellPhoneNum:(NSString *)num
{
    if (num.length == 0) {
        return NO;
    }else{
        if (num.length == 11) {
            return YES;
        }else{
            return NO;
        }
    }
    
    
//    NSString *pa = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0-9]))\\d{8}$";
//    NSRange range =  [num rangeOfString:pa options:NSRegularExpressionSearch];
//    if (range.location != NSNotFound) {
//        return YES;
//    }else{
//        return NO;
//    }
}

//检查邮箱格式
+ (BOOL)checkEmail:(NSString *)text{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    
    return [emailTest evaluateWithObject:text];
}

//检查身份证格式
+ (BOOL)checkIDNumber:(NSString *)text{
    //长度不为18的都排除掉
    if (text.length!=18) {
        return NO;
    }
    
    //校验格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    BOOL flag = [identityCardPredicate evaluateWithObject:text];
    
    if (!flag) {
        return flag;    //格式错误
    }else {
        //格式正确在判断是否合法
        
        //将前17位加权因子保存在数组里
        NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
        
        //这是除以11后，可能产生的11位余数、验证码，也保存成数组
        NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
        
        //用来保存前17位各自乖以加权因子后的总和
        NSInteger idCardWiSum = 0;
        for(int i = 0;i < 17;i++)
        {
            NSInteger subStrIndex = [[text substringWithRange:NSMakeRange(i, 1)] integerValue];
            NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
            
            idCardWiSum+= subStrIndex * idCardWiIndex;
            
        }
        
        //计算出校验码所在数组的位置
        NSInteger idCardMod=idCardWiSum%11;
        
        //得到最后一位身份证号码
        NSString * idCardLast= [text substringWithRange:NSMakeRange(17, 1)];
        
        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        if(idCardMod==2)
        {
            if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
            {
                return YES;
            }else
            {
                return NO;
            }
        }else{
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
            {
                return YES;
            }
            else
            {
                return NO;
            }
        }
    }
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES)
        || ([regextestphs evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//+ (BOOL)validateMobile:(NSString *)mobileNum{
//    
//    /**
//     
//     * 手机号码
//     
//     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//     
//     * 联通：130,131,132,152,155,156,185,186
//     
//     * 电信：133,1349,153,180,189
//     
//     */
//    
//    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
//    
//    /**
//     
//     10         * 中国移动：China Mobile
//     
//     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//     
//     12         */
//    
//    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
//    
//    /**
//     
//     15         * 中国联通：China Unicom
//     
//     16         * 130,131,132,152,155,156,185,186
//     
//     17         */
//    
//    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
//    
//    /**
//     
//     20         * 中国电信：China Telecom
//     
//     21         * 133,1349,153,180,189
//     
//     22         */
//    
//    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
//    
//    /**
//     
//     25         * 大陆地区固话及小灵通
//     
//     26         * 区号：010,020,021,022,023,024,025,027,028,029
//     
//     27         * 号码：七位或八位
//     
//     28         */
//    
//    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
//    
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    
//    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
//    
//    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
//    
//    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
//    
//    if(([regextestmobile evaluateWithObject:mobileNum] == YES)
//       
//       || ([regextestcm evaluateWithObject:mobileNum] == YES)
//       
//       || ([regextestct evaluateWithObject:mobileNum] == YES)
//       
//       || ([regextestcu evaluateWithObject:mobileNum] == YES))
//    {
//        return YES;
//    }else{
//        return NO;
//        }
//}

+(NSString *)timeStringWithDate:(NSDate *)date isCustomFriendList:(BOOL)isList {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDate * now = [NSDate date];
    //    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //    NSInteger interval = [zone secondsFromGMTForDate:now];
    //    NSDate *localDate = [now dateByAddingTimeInterval:interval];
    NSDateComponents *components = [calendar components:
                                    NSCalendarUnitYear|
                                    NSCalendarUnitMonth|
                                    NSCalendarUnitWeekOfYear|
                                    NSCalendarUnitDay|
                                    NSCalendarUnitHour|
                                    NSCalendarUnitMinute|
                                    NSCalendarUnitSecond
                                               fromDate:date
                                                 toDate:now
                                                options:0];
    [components setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    
    NSLog(@"%@",components);
    
    if (components.year >= 1)
    {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        return [dateFormatter stringFromDate:date];
        
    }
    else if (components.month >= 1)
    {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        return [dateFormatter stringFromDate:date];
        
    }
    else if (components.weekOfYear >= 1)
    {
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        return [dateFormatter stringFromDate:date];
        
    }
    else if (components.day >= 1)    // up to 6 days ago
    {
        if (components.day == 1)
        {
            if (isList) {
                return @"昨天";
            }else{
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                dateFormatter.dateFormat = @"HH:mm";
                return [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:date]];
            }
        }
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"MM-dd";
        return [dateFormatter stringFromDate:date];
        
    }else if (components.hour >= 1)   // up to 23 hours ago
    {
        if (isList) {
            NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.dateFormat = @"yyyy-MM-dd";
            NSString *newString = [dateFormatter stringFromDate:date];
            NSString *oldString = [dateFormatter stringFromDate:now];
            if (![newString isEqualToString:oldString]) {
                return @"昨天";
            }else{
                return [NSString stringWithFormat:@"%ld小时前",components.hour];
            }
        }else{
            if (components.hour == 1)
            {
                return @"1小时前";
            }
            if (isList) {
                NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                dateFormatter.dateFormat = @"HH:mm";
                return [dateFormatter stringFromDate:date];
            }
            return [NSString stringWithFormat:@"%ld小时前",(long)components.hour];
        }
    }
    else if (components.minute >= 1) // up to 59 minutes ago
    {
        if (components.minute == 1)
        {
            return @"1分钟前";
        }
        return [NSString stringWithFormat:@"%ld分钟前",(long)components.minute];
    }
    else if (components.second < 5)
    {
        return @"刚刚";
    }
    
    // between 5 and 59 seconds ago
    return [NSString stringWithFormat:@"%ld秒前",(long)components.second];
    
}




//返回当前时间的字符串信息
+(NSString*)getStringWithNowTime{
    //得到当前系统日期
    NSDate *date = [NSDate date];
    //然后您需要定义一个NSDataFormat的对象
    NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];
    //然后设置这个类的dataFormate属性为一个字符串，系统就可以因此自动识别年月日时间
    dateFormat.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    //之后定义一个字符串，使用stringFromDate方法将日期转换为字符串
    NSString * dateToString = [dateFormat stringFromDate:date];
    return dateToString;
}

//返回当前时间 去除8小时误差
+ (NSDate *)getLocalDateNow{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger integer = [zone secondsFromGMTForDate:date];
    NSDate *localDate = [date dateByAddingTimeInterval:integer];
    return localDate;
}


//返回time时间的date类型
+(NSDate*)getDateWithString:(NSString *)time{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,这里可以设置成自己需要的格式
    
    NSDate *date =[dateFormat dateFromString:time];
    return date;
}

//返回当天零点时间
+ (NSDate *)zeroDateOfToday{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:[NSDate date]];
    components.hour = 0;
    components.minute = 0;
    components.second = 0;
    
    // components.nanosecond = 0 not available in iOS
    NSTimeInterval ts = (double)(int)[[calendar dateFromComponents:components] timeIntervalSince1970];
    return [[NSDate dateWithTimeIntervalSince1970:ts] dateByAddingTimeInterval:60*60*8];
}

//裁剪图片
+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation ==UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform =CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        caseUIImageOrientationDown:
        caseUIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        caseUIImageOrientationLeft:
        caseUIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width,0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        caseUIImageOrientationRight:
        caseUIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width,0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height,0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx =CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                            CGImageGetBitsPerComponent(aImage.CGImage),0,
                                            CGImageGetColorSpace(aImage.CGImage),
                                            CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx,CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx,CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg =CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

/**
 *  生成图片
 *
 *  @param color  图片颜色
 *  @param height 图片高度
 *
 *  @return 生成的图片
 */
+ (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}
//将图片变灰
+ (UIImage*)getGrayImage:(UIImage*)sourceImage
{
    int width = sourceImage.size.width;
    int height = sourceImage.size.height;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    
    if (context == NULL) {
        return nil;
    }
    
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
    UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
    CGContextRelease(context);
    
    return grayImage;
}

//图片压缩到指定大小 比下面的好用
+ (UIImage *)imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)defineSize
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineSize.width;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//图片压缩到指定大小
+ (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize fromImage:(UIImage *)oldImage
{
    UIImage *sourceImage = oldImage;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    return thumbnailImage;
}

+ (NSString *)jsonFromArray:(NSArray *)aArray
{
    NSData *data=[NSJSONSerialization dataWithJSONObject:aArray
                                                 options:NSJSONWritingPrettyPrinted
                                                   error:nil];
    if (data == nil) {
        
        return nil;
    }
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    //去除字符串中的换行符
    NSString *replaceStr = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return replaceStr;
}

+ (NSArray *)josnToArray:(NSString *)jsonStr{
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSArray *obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    
    return obj;
}

//字典转字符串
+ (NSString *)dictionaryToJson:(NSDictionary *)dict
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSDictionary *)countDayWithTotalDay:(NSInteger)totalDay nowDay:(NSInteger)nowDay month:(NSInteger)month{
    NSMutableArray *dayArray = [NSMutableArray array];
    NSMutableArray *monthArray = [NSMutableArray array];
    if ((nowDay + 6) > totalDay) {
        NSInteger temp = nowDay - 1;
        for (int i = 0; i < totalDay - nowDay + 1; i++) {
            temp += 1;
            [dayArray addObject:@(temp)];
            [monthArray addObject:@(month)];
        }
        NSInteger newDay = 0;
        for (int i = 0; i < 6 - (totalDay - nowDay); i++) {
            newDay += 1;
            [dayArray addObject:@(newDay)];
            [monthArray addObject:@(month + 1 > 12 ? 1 : month + 1)];
        }
    }else {
        for (int i = 0; i < 7; i++) {
            if (i == 0) {
                nowDay += i;
            }else{
                nowDay += 1;
            }
            [dayArray addObject:@(nowDay)];
            [monthArray addObject:@(month)];
        }
    }
    return @{@"day":dayArray,@"month":monthArray};
}

//+ (NSDictionary *)dateWithDateString:(NSString *)string {
//    NSDictionary *dateDict = [NSDictionary dictionary];
//    NSArray *startDate = [NSString subStringWithDateString:string];
//    NSInteger month = [startDate[1] integerValue];
//    NSInteger day = [startDate[2] integerValue];
//    if (month == 4 || month == 6 || month == 9 || month == 11) {
//        dateDict = [self countDayWithTotalDay:30 nowDay:day month:month];
//    }else if (month == 2) {
//        if ([NSString isLeapYearWithYearString:startDate[0]]) {
//            dateDict = [self countDayWithTotalDay:29 nowDay:day month:month];
//        }else{
//            dateDict = [self countDayWithTotalDay:28 nowDay:day month:month];
//        }
//    }else {
//        dateDict = [self countDayWithTotalDay:31 nowDay:day month:month];
//    }
//    return dateDict;
//}

#pragma mark - 系统相机方法
+(void)takePhoto:(id<UINavigationControllerDelegate,UIImagePickerControllerDelegate>)delegate
{
    //判断设备是否存在摄像头，有就调用系统相机，没有，就提醒用户
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        //创建相机
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        //文件由来
        picker.sourceType = UIImagePickerControllerSourceTypeCamera; //指定数据来源来自于相机
        if(iOS8Later) {
            picker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        picker.delegate  = delegate;// 指定代理
        picker.allowsEditing = NO; //允许编辑
        //模态弹出
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
    }else{
        //没有摄像头，提醒用户 您的设备没有摄像头
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您的设备没有摄像头" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
        [alertController addAction:alertAction1];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    }
}

+ (UIViewController *)getCurrentVCWithSubView:(UIView *)subView
{
    for (UIView* next = [subView superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}



/** 获取当前屏幕显示的viewcontroller */
+(UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    
    if([result isMemberOfClass:[UITabBarController class]]) {
        UITabBarController *tabbarVC = (UITabBarController *)result;
        
        UIViewController *selectedVC = tabbarVC.viewControllers[tabbarVC.selectedIndex];
        if([selectedVC isMemberOfClass:[UINavigationController class]]) {
            UINavigationController *nav = (UINavigationController *)selectedVC;
            return [nav.viewControllers lastObject];
        }
        
        return selectedVC;
        
    }else if([result isMemberOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)result;
        
        return [nav.viewControllers lastObject];
    }
    return result;
}


+(void)removeFileWithPath:(NSString *)path
{
    if([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        BOOL blDele= [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        if (blDele) {
//            DLog(@"dele success");
        }else {
//            DLog(@"dele fail");
        }
    }
}

+(NSString *)saveFileWithData:(NSData *)data fileName:(NSString *)name
{
    NSString *tmpDir = NSTemporaryDirectory();
    
    NSString *filePath = [tmpDir stringByAppendingPathComponent:name];
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        
        if([[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil] && [data writeToFile:filePath atomically:YES]) {
            return filePath;
        }else {
            return nil;
        }
    }else {
        return filePath;
    }
}

+(void)urlFromPHAsset:(PHAsset *)phasset completion:(void (^)(NSData *))completion
{
    // 获取一个资源（PHAsset）
    PHAsset *phAsset = phasset;
    if (phAsset.mediaType == PHAssetMediaTypeVideo) {
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            
            NSURL *url = urlAsset.URL;
            
            NSData *data = [NSData dataWithContentsOfURL:url];
            
            if(completion) {
                completion(data);
            }
            
        }];
    }
}
#pragma mark ---- 将时间戳转换成时间

+ (NSString *)getTimeFromTimestamp:(NSInteger)time{
	
	//将对象类型的时间转换为NSDate类型
	
	NSDate * myDate=[NSDate dateWithTimeIntervalSince1970:time];
	
	//设置时间格式
	
	NSDateFormatter * formatter=[[NSDateFormatter alloc]init];
	
	[formatter setDateFormat:@"YYYY年MM月dd日 HH:mm"];
	
	//将时间转换为字符串
	
	NSString *timeStr=[formatter stringFromDate:myDate];
	
	return timeStr;
	
}

@end
